//app.js
var util = require('utils/util.js');
App({
  onLaunch: function () {
    var that = this;
    //小程序初始化先判断用户是否登录    
      wx.checkSession({
        success: function(){  
          wx.getStorage({  
            key: 'userInfo',
            success: function(res) {
                that.globalData.userInfo = res.data;
                that.globalData.sessionId = wx.getStorageSync('sessionId');
            },
            fail:function() {
              that.login();
            }
          });
        },
        fail: function(){
          //登录态过期
          that.login() //重新登录
        }
      })
  },
  login:function(){
    wx.reLaunch({
      url: '/pages/toLogin/toLogin'
    })
  },
  getUserInfo:function(){
    var that = this;
      wx.getUserProfile({
        desc: '用于完善会员资料',
        success:function(userInfoRes){
          console.log('wx.getUserProfile', userInfoRes);
          that.globalData.userInfo=userInfoRes.userInfo;
          wx.login({
            success:function(res){
               //换取openid & session_key
              util.req("WxOpen/Login",{
                code:res.code,
                rawData:userInfoRes.rawData} ,function(result){
                  console.log('wx.login - request-/WxOpen/OnLogin Result:', result);
                if(result.success){
                  wx.setStorageSync('sessionId', result.data.sessionId);
                  wx.setStorageSync('userInfo', result.data.userInfo);
                  that.globalData.sessionId=result.data.sessionId;
                  that.globalData.userInfo=result.data.userInfo;
                  wx.reLaunch({
                    url: '/pages/index/index'
                  });
                }else{
                  console.log('储存session失败！',result);
                  that.login() //重新登录
                }
              })
            }
          });
        }
      }) 
  },
  setUserInfo:function(data){   //将用户信息缓存保存
    this.globalData.userInfo = data;
    wx.setStorage({
      key:"userInfo",
      data:data
    })
  },
  globalData:{
    userInfo:null,
    sessionId:null,
  }
})
 